/*
 * Copyright (c) 2010 Curtis Boyden.  All rights reserved. 
 * This software was developed by Curtis Boyden and is provided under the terms 
 * of the GNU Lesser General Public License, Version 2.1. You may not use 
 * this file except in compliance with the license. If you need a copy of the license, 
 * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is ejMud
 * (Ewerp Java MUD).  The Initial Developer is Curtis Boyden.
 *
 * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" 
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to 
 * the license for the specific language governing your rights and limitations.
*/

package com.ewerp.mud.communications;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

import com.ewerp.mud.commands.parsers.StringCommandParser;
import com.ewerp.mud.core.session.ISessionManager;

public class ServerSocketHandler implements Runnable {

    protected ServerSocket serverSocket = null;
    protected int port = 5555;
    protected ISessionManager sessionManager = null;
    protected Boolean shutdown = false;
    
    @Override
    public void run() {
        try {
        	StringCommandParser.init();
        	
            if(serverSocket == null) {
                serverSocket = new ServerSocket(port);
            }
            
            serverSocket.setSoTimeout(2000);
            
            Socket client = null;
            
            while(!isShutdown()) {
                try {
                    client = serverSocket.accept();
                    
                    // TODO: Check for blacklist
                    sessionManager.registerSession(new SocketSession(client));
                } catch(SocketTimeoutException e) {
                    // This exists to allow the polling of the isShutdown state
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public ISessionManager getSessionManager() {
        return sessionManager;
    }
    
    public void setSessionManager(ISessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }
    
    public ServerSocket getServerSocket() {
        return serverSocket;
    }
    
    public void setServerSocket(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }
    
    public boolean isShutdown() {
        synchronized(shutdown) {
            return shutdown;
        }
    }
    
    public void setShutdown(boolean shutdown) {
        synchronized(this.shutdown) {
            this.shutdown = shutdown;
        }
    }

}
